'''
Created on May 11, 2011

@author: yc30v1m
'''
from library.executors.TestCase import TestCase
from plugins.FlatFiles.Reader import Reader
import os
from logging import getLogger
#Demo Component
from plugins.ProgressBarClass import ProgressBarClass

log = getLogger(__name__)


class MultipleRows(TestCase):
    '''
    classdocs
    '''
    _fileRows = None
    _fileHasHeader = False
    _step = 1
    _pb = None
       
    def __init__(self, testCaseAsDict):
        '''  
        Every class extending (TestCase) class should have this 
        function and should call super class constructor to instantiate base class 
        '''
        super(self.__class__, self).__init__(testCaseAsDict)
             
        
    def executeTestSteps(self):
        try:
            self.getInputFileAsList()
            # For Visual Progress
            totalRows = len(self._fileRows)
            self._pb = ProgressBarClass(totalRows)
            i = 0
            # For Visual Progress
            if totalRows>0:
                for i in range(i,totalRows,self._step):
                    
                    self._pb.progress(i+1)
                    
                    self.validateSingleRow(self._fileRows[i])
                    
                self.testCaseResults()
            else:
                #print "File has no records hence corresponding test case are not executed"
                return
        except Exception as e:
            self.testCaseFailedOnce()
            self.testCaseResults()
            log.debug('Exception occurred in multiple row validation',+e)
            log.debug("Exception occured" + str(self.tcid))
            
    def validateSingleRow(self, row):
        try:
            primaryCol = self.getTestCaseOption("PRIMARY_COLUMN")
            validateCol = self.getTestCaseOption("VALIDATE_COLUMN")
            dbName = self.getTestCaseOption('DATABASE')
            dbQuery = self.getTestCaseOption('QUERY')
            dbQueryReplaceText = self.getTestCaseOption('QUERY_REPLACE_TEXT')
            
            replacementValue = None
            if self._fileHasHeader==False:
                replacementValue = row['COLUMN-' + str(primaryCol)]
                validationValue = row['COLUMN-' + str(validateCol)]
            if self._fileHasHeader==True:
                replacementValue = row[str(primaryCol)]
                validationValue = row[str(validateCol)]
            
            if replacementValue != None:
                query = self.replaceQueryWithValue(dbQuery, dbQueryReplaceText, replacementValue)
                queryResult = self.runSingleRowQuery(query, dbName)
                if queryResult!= None:
                    for k,v in queryResult.items():
                        if (v != validationValue) and (v!='NULL'):
                            self.addTestExecutionNotes('primaryKey=' + str(replacementValue) + ', dbValue=' + v + ', FileValue=' + validationValue)
                            self.testCaseFailedOnce()
                        else:
                        #we have do nothing for this as it pass
                            pass
                else:

                        self.addTestExecutionNotes('primaryKey=' + str(replacementValue) + ', dbValue=' + str(queryResult) + ', FileValue=' + validationValue)
                        self.testCaseFailedOnce()
           
        except:
            self.testCaseFailedOnce()
            log.critical("Unable to Validate Single Row : " + str(row))

    @staticmethod
    def supportedExecutionTypes(tcTypes):
        '''  
        Every class extending (TestCase) class should have this function 
        The Automation script will read  
        '''
        return tcTypes in ["CSVValidation", "MultipleRowsValidation", "MultipleRows"]
    
    def getInputFileAsList(self):
        csvObj = Reader(self.testCase['FULL_FILE_NAME'])
        self._fileRows = csvObj.processToListWithDictCols()
        if len(self._fileRows)>0:
            print "Executing TestCase ::  " + str(self.tcid)
        else:
            print "NO records found in "+str(self.testCase['FULL_FILE_NAME'] +" hence corresponding test case not executed")
        self._fileHasHeader = csvObj.hasHeader()
        self._fileHasHeader=False

    

    
        
